import React, { Component } from 'react'
import IceContainer from '@icedesign/container';
// import DataBinder from '@icedesign/data-binder';
import { Select, Button, Radio, Feedback } from '@icedesign/base';
import { generateProfitChartOption } from '../../../../echarts-figures.js';
import './FreeDrawChart.scss';
import filterData from '../../filterData';
// import PropTypes from 'prop-types'

import axios from 'axios';

var echarts = require('echarts');
const { Group: RadioGroup } = Radio; 
const Toast = Feedback.toast;
let itemArr = [];

export default class FreeDrawChart extends Component {

  static propTypes = {
    // secu_code: PropTypes.string.isRequired,
  };
  
  constructor(props) {
    super(props);
    let id = ( '_' + Math.random()).replace('.','_');
    this.state = {
        chartId : 'profitChart',
        companyname:'',
        secu_code:this.GetUrlParam("secu_code"),
        value: '',
        item: '',
        itemCheck:[],
        list: ["营业收入", "利息收入", "营业成本", "利息支出", "营业税金及附加", "销售费用", "管理费用", "财务费用", "资产减值损失", "公允价值变动收益", "投资收益", "对联营企业和合营企业的投资收益", "汇兑收益", "营业利润", "营业外收入", "营业外支出", "所得税费用", "净利润", "销售商品、提供劳务收到的现金", "收到其他与经营活动有关的现金", "购买商品、接受劳务支付的现金", "支付给职工以及为职工支付的现金", "支付的各项税费", "支付其他与经营活动有关的现金", "收回投资收到的现金", "取得投资收益收到的现金", "处置固定资产、无形资产和其他长期资产收回的现金净额", "处置子公司及其他营业单位收到的现金净额", "收到其他与投资活动有关的现金", "购建固定资产、无形资产和其他长期资产支付的现金", "投资支付的现金", "取得子公司及其他营业单位支付的现金净额", "支付其他与投资活动有关的现金", "交易性金融资产", "其他流动资产", "可供出售金融资产", "长期股权投资", "固定资产", "在建工程", "无形资产", "商誉", "长期待摊费用", "递延所得税资产", "其他非流动资产", "资产总计", "短期借款", "应付票据", "应付账款", "预收账款", "一年内到期的非流动负债", "流动负债合计", "长期借款", "应付债券", "长期应付款", "递延所得税负债", "其他非流动负债", "非流动负债合计", "实收资本(或股本)", "资本公积", "盈余公积", "未分配利润", "少数股东权益", "货币资金", "预付账款", "存货", "应收账款", "应收票据", "其他应收款", "应付职工薪酬", "其他应付款"],
        currentTime:'q1',
        timeParam:'单季度',
        numbers:{},
        count: 0,
        radioValue:'',
        visible: false
    }
  }
  initChart(config,a) {
    let myChart = echarts.getInstanceByDom(document.getElementById(this.state.chartId));
    if( myChart === undefined){
        myChart = echarts.init(document.getElementById(this.state.chartId));
    }
    if(a){
      myChart.setOption(config,true);
    }else{
      myChart.setOption(config);
    }
  }

  GetUrlParam(paraName) {
  　var url = document.location.toString();
  　var arrObj = url.split("?");
  　　　if (arrObj.length > 1) {
  　　　　　var arrPara = arrObj[1].split("&");
  　　　　　var arr;
  　　　　　for (var i = 0; i < arrPara.length; i++) {
  　　　　　　　arr = arrPara[i].split("=");
  　　　　　　　if (arr != null && arr[0] == paraName) {
  　　　　　　　　　return arr[1];
  　　　　　　　}
  　　　　　}
  　　　　　return "";
  　　　}
  　　　else { return ""; }
  }

  Check(arr){
    if(this.state.itemCheck.indexOf(arr)==-1){
      itemArr.push(arr)
      this.setState({
        itemCheck:itemArr
      })
      return false
    }else{
      return true
    }
  }

  getData = () =>{
    let arr = `${this.state.item}-${this.state.currentTime}-${this.state.value}`;
    // this.Check(arr);
    // console.log("secu_code",localStorage.getItem("secu_code"))
    if(this.Check(arr)){
      this.show("您已经绘制相同参数图表")
    }else{
      axios({
        // cattle/drawing_tools?secu_code=000001&company_code=000002
        url: `${global.constants.GOLDEYEGETHOST}cattle/drawing_tools`,
        method: 'get',
        params: {
          // secu_code: localStorage.getItem("TOKEN"),
          secu_code:GetUrlParam("secu_code"),
          // item: this.state.item,
          // time_flag: this.state.currentTime,
          // compare: this.state.value
        }
      })
      .then((response) => {
        // console.log("response",response)
        if(response.data.msg != 'success' || !response.data.data){
          this.show(response.data.msg)
          // this.setState({
          //   visible: true
          // });
        }else{
          const chartData = filterData(response.data.data, this.state);
          if(!chartData || !chartData.data) {
            return  this.show("暂无数据");
          }
          if(this.state.count == 0){
            let name = '';
            if(this.state.value.length !==0 ){
              name = this.state.item + '-' + this.state.value + '-' + this.state.timeParam;
            }else{
              name = this.state.item + '-' + this.state.timeParam;
            }
            this.setState({
              count: 1,
              numbers:generateProfitChartOption(
                "自由作图区",
                name,
                chartData.data.dates,
                chartData.data.values,
                this.state.radioValue
              )
            });
            // console.log("leftChart3",response.data.data)
          }else{
            let name = '';
            if(this.state.value.length !==0 ){
              name = this.state.item + '-' + this.state.value + '-' + this.state.timeParam;
            }else{
              name = this.state.item + '-' + this.state.timeParam;
            }
            // console.log("leftChart4",response.data.data)
            this.setState(prevState=>{
                numbers:prevState.numbers.series.push({
                name: name,
                type:'line',
                smooth: true,
                data:chartData.data.values,
                xAxis:{
                  data:chartData.data.dates,
                },
              })
            });
          }
          this.initChart(this.state.numbers);
        }
        })
      .catch((error) => {
        console.log(error);
      });
    }

  }
  
  // componentDidMount(){

  // }

  onSelectChange (value) {
    if(value == '单季度'){
      this.setState({
        currentTime: 'q1'
      })
    }else{
      this.setState({
        currentTime: 'q4'
      })
    }
    this.setState({
        timeParam:value,
    })
  }

  onSelectItem (values) {
    this.setState({
      item:values,
    })
  }

  onRadioChange(value) {
    if(value !== '原始数据'){
      this.setState({
        value: value
      })
    }else{
      this.setState({
        value: ''
      })
    }
    this.setState({
        radioValue: value
    });     
  }

  onSubmit() {
    this.getData();
  }

  onResetItem(){
    this.setState({
      radioValue: '',
      item: ''
    })
  }

  show = (content) => {
    Toast.show({
      type: "error",
      content: content,
      afterClose: () => console.log("")
    });
  };

  // handleClose() {
  //   this.setState({
  //     visible: false
  //   });
  // }

  onResetArea(){
    if(JSON.stringify(this.state.numbers)!='{}'){
      this.state.numbers.series.map(number=>{
        number.data = null;
        number.name = null;
      });
      this.state.numbers.legend = {
        x: '80%',
        y: '5%'
      }
      itemArr = []
      this.setState({
        numbers:{},
        count:0,
        itemCheck:itemArr
      });
      this.initChart(this.state.numbers,true);
    }
  }

  render() {
    const time=['单季度','一年']
    return (
      <div className="chart-container" style={{width:'50%',float:'left',marginRight:'15px'}}>
        <IceContainer style={{borderRadius:'0'}}>
          <div style={{height:'160px'}}>
          <div style={{float:'left'}}>
            <div style={{height:'43px',marginBottom:'30px'}}>
                <div style={{height:'48px'}}>当前公司：{localStorage.getItem("secu_abbr")}</div>
                <div style={{float:'left',height:'48px'}}>
                  <span style={{float:'left',marginTop:'5px'}}>选择展示的科目:</span>
                  <Select
                    style={{width: "200px", margin:"0 20px",float:'left'}}
                    size="large"
                    multiple={false}
                    // showSearch={true}
                    value={this.state.item}
                    onChange={this.onSelectItem.bind(this)}
                    dataSource={this.state.list}
                  />
                </div> 
                <Select
                  style={{width: "50px",marginTop:'1px'}}
                  size="large"
                  value={this.state.timeParam}
                  onChange={this.onSelectChange.bind(this)}
                  dataSource={time}
                />
            </div>
            <div>
              <RadioGroup value={this.state.radioValue} onChange={this.onRadioChange.bind(this)}>
                <Radio id="origin" value="原始数据">
                    原始数据
                </Radio>
                <Radio id="tong" value="同比">
                    同比
                </Radio>
                <Radio id="ring" value="环比">
                    环比
                </Radio>
                <Radio id="profit" value="净利润占比">
                    净利润占比
                </Radio>
                <Radio id="cash" value="营业收入占比">
                    营业收入占比
                </Radio>
                <Radio id="asset" value="总资产占比">
                    总资产占比
                </Radio>
              </RadioGroup>
              <div style={{margin:'15px 0 0 10px'}}>
                <Button style={{margin:'3px 0 30px 30px'}} onClick={this.onSubmit.bind(this)}>提交</Button>
                <Button style={{margin:'3px 0 30px 30px'}} onClick={this.onResetItem.bind(this)}>重置选项</Button>
                <Button style={{margin:'3px 0 30px 30px'}} onClick={this.onResetArea.bind(this)}>重置作图区</Button>
              </div> 
            </div>
            </div>
            {/* <div style={{float:'left',margin:'20px 0 0 30px'}}>
                <Notice
                  style={{width:'2 d00px',margin:'0 auto'}}
                  type="warning"
                  visible={this.state.visible}
                  title="没有获取到数据"
                  // closable={true}
                  // onClose={this.handleClose.bind(this)}
                  animation={false}
               />
            </div> */}
            
          </div>
          <div id={this.state.chartId} style={{width: "100%", height: "500px"}}>
              {this.state.message && 
              <div style={{
                  fontSize: '25px',
                  height: '500px',
                  lineHeight: '500px',
                  textAlign: 'center'
              }}>
                  没有相关数据
              </div>
              }
          </div>
        </IceContainer>
      </div>
    )
  }
}
